# system
import os

# app-engine
from google.appengine.ext import db
from google.appengine.api import users

SHARD_PREFIX = "5-19-final-"
MAX_SHARD_ID = 28

def GetShardFromId(id):
  try:
    num = int(id)
  except ValueError:
    num = 0
  if (num > MAX_SHARD_ID):
    num = MAX_SHARD_ID
  return "%s%05d" % (SHARD_PREFIX, num)

def GetAllShardIds():
  return [ str(x) for x in xrange(0, MAX_SHARD_ID + 1) ]

# Schema of Person object
class Person(db.Model):
  name = db.StringProperty(multiline=False)
  sex = db.StringProperty(multiline=False)
  age = db.StringProperty(multiline=False)
  contact = db.StringProperty(multiline=False)
  address = db.StringProperty(multiline=False)
  unit = db.StringProperty(multiline=False)
  status = db.StringProperty(multiline=False)
  other = db.StringProperty(multiline=False)
  hospital = db.StringProperty(multiline=False)
  section = db.StringProperty(multiline=False)
  hospital_contact = db.StringProperty(multiline=False)
  source = db.StringProperty(multiline=False)
  shard = db.StringProperty(multiline=False)
  pid = db.StringProperty(multiline=False)
  last_update = db.DateTimeProperty(auto_now=True)

# Schema of snapshot object
class Snapshot(db.Model):
  snapshot = db.BlobProperty()
  live = db.BooleanProperty()
  num_entries = db.IntegerProperty()
  creation_time = db.DateTimeProperty(auto_now_add=True)
  state = db.StringProperty(multiline=False)

# Schema of snapshot object
class PersonList(db.Model):
  list = db.ListProperty(db.Key)

# Final template to display persons related page
def GetPersonsTemplate(req_handler, persons):
  if users.get_current_user():
    url = users.create_logout_url(req_handler.request.uri)
    url_linktext = 'Logout'
  else:
    url = users.create_login_url(req_handler.request.uri)
    url_linktext = 'Login'

  template_values = {
    'persons': persons,
    'url': url,
    'url_linktext': url_linktext,
    'is_admin': users.is_current_user_admin(),
  }
  return template_values

# Returns the template path of html
def GetTemplatePath(html):
  return os.path.join(os.path.dirname(__file__),
                      'templates/%s' % html)

# Returns template for browsing all persons sorted by last update
# and fitered by shard.
#   req_handler: RequestHandler
#   offset: number of persons to display in each page
def GetPersonsPaginationTemplate(req_handler, offset):
  start = req_handler.request.get("start")
  shard_id = req_handler.request.get("shard")
  if start:
    start = int(start)
  else:
    start = 0

  if not shard_id:
    shard_id = '0'

  # Fetch persons with limit=offset sort by last_update filtered by shard
  query = Person.all().filter('shard =', GetShardFromId(shard_id))
  persons = query.order('-last_update').fetch(offset, start)
  template_values = GetPersonsTemplate(req_handler, persons)

  # set shards
  template_values['current_shard'] = shard_id
  template_values['shards'] = GetAllShardIds()

  # maybe show next link
  if len(persons) < offset:
    template_values['show_next'] = False
  else:
    template_values['show_next'] = True
    template_values['next'] = start + offset
  
  # maybe show prev link
  if start == 0:
    template_values['show_prev'] = False
  else:
    template_values['show_prev'] = True
    prev = start - offset
    if prev < 0 : prev = 0
    template_values['prev'] = prev

  template_values['tab'] = "\t"
  template_values['newline'] = "\n"
  return template_values

